package com.zhouzi.zhaoyang.ui.activity

import android.content.Intent
import android.os.Build
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.animation.AnimationUtils
import android.widget.Toast
import com.afollestad.materialdialogs.MaterialDialog
import com.zhouzi.zhaoyang.R
import com.zhouzi.zhaoyang.base.BaseActivity
import com.zhouzi.zhaoyang.bean.AdvertBean
import com.zhouzi.zhaoyang.bean.LoginBean
import com.zhouzi.zhaoyang.bean.OrderDetailBean
import com.zhouzi.zhaoyang.mvp.p.MainActivityPresenter
import com.zhouzi.zhaoyang.mvp.v.IMainActivityView
import com.zhouzi.zhaoyang.service.VoiceService
import com.zhouzi.zhaoyang.util.*
import com.zhouzi.zhaoyang.util.print.PrinterUtil
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*


class MainActivity : BaseActivity(), IMainActivityView {
    override fun errorToken() {
        exitToLogin()
    }
    override fun getLastOrderPrintSuccess(data: OrderDetailBean?) {
        var mode: Int = SPUtils.getInstance().getValue("printMode", 1) as Int
        val util = PrinterUtil(this)
        val line = ArrayList<String>()

        if (data != null){
            for (index in 1..mode){
                line.add("补打 ")
                line.add("门店名称: "+ data.storeName)
                line.add("商户单号: "+data.outTradeNo)
                line.add(PrintFormatUtils.getQrCodeCmd(data.outTradeNo)+"\n\n")
                line.add("订单金额："+  Calculator.fen2Yuan(data.totalFee!!.toLong()))
                if (data.settlementTotalFee!! > 0 ){
                    line.add("实收金额："+Calculator.fen2Yuan(data.settlementTotalFee!!.toLong()))
                }
                line.add("实付金额："+  Calculator.fen2Yuan(data.realFee!!.toLong()))
                line.add("支付方式："+data.payType)
                line.add("支付状态："+data.status)
//            line.add("设备号："+data.deviceNo)
                if (!TextUtils.isEmpty(data.userName)){
                    line.add("店员："+data.userName)

                }

                line.add("下单时间: "+data.orderTime)
//            line.add("打印时间："+date[0]+"-"+date[1]+"-"+date[2] +"   "+date[3] +":"+date[4]+":"+date[5])
                line.add("签名："+"\n\n\n\n" +
                        "\n" +
                        "\n")


            }

            util.createData(line)

        }
    }

    override fun getLastOrderPrintFailed(imgUrl: String?) {
        Toast.makeText(mContext, imgUrl, Toast.LENGTH_SHORT).show()
    }


    var vip: Boolean = true


    override fun getAppQrCodeFailed(imgUrl: String?) {
        Log.e("getAppQrCodeFailed：", imgUrl)
        Toast.makeText(mContext, imgUrl, Toast.LENGTH_SHORT).show()
    }

    override fun getAppQrCodeSuccess(imgUrl: String?) {
        webView.visibility = VISIBLE
        webView.loadUrl(imgUrl)
        bannerMain.visibility = GONE
    }


    override fun getAdvertSuccess(data: AdvertBean?) {
//        data?.let {
//        }
    }

    /*静止超过N秒将自动进入屏保*/
    private val mHoldStillTime = 13000
    /* banner 轮播间隔时间*/
    private val intervalTime = 3000

    private val p = MainActivityPresenter()

    init {
        p.attachView(this)
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_main
    }


    var timer = Timer()
    private var countDown = 60
    private fun countDown() {

         var timerTask: TimerTask = object : TimerTask() {
            override fun run() {
                runOnUiThread(Runnable {

                    countDown--

                    if (countDown == 0) {
                        timer.cancel()

                        webView.visibility = GONE
                        bannerMain.visibility = VISIBLE
                        frameTitle.visibility = GONE
                        view.visibility = GONE

                    }


                })
            }
        }


        timer.schedule(timerTask, 1000, 1000)

    }




    override fun initView() {


//        SPUtils.getInstance().putValue("printMode", 1)

        viewClick()

        p.getAdvertList(Build.SERIAL)


    }



    var turnSettings = false
    var settingsCount = 0
    private fun viewClick() {

        tvMainPayMoney.setOnClickListener {
            val animation = AnimationUtils.loadAnimation(mContext, R.anim.animation_scale)
            tvMainPayMoney.startAnimation(animation)
        }

        btnConnUsb.setOnClickListener {
            // todo
            p.getAppQrCode(Build.SERIAL)
            frameTitle.visibility = VISIBLE
            webView.visibility = VISIBLE
            bannerMain.visibility = GONE
            tvApBtn.visibility = VISIBLE
            view.visibility = VISIBLE





            countDown()


        }

        tvApBtn.setOnClickListener {
            frameTitle.visibility = GONE
            webView.visibility = GONE
            bannerMain.visibility = VISIBLE
            tvApBtn.visibility = GONE
            view.visibility = GONE

        }


        var data = intent.getParcelableExtra<LoginBean>("personInfo")


        btnSettings.setOnClickListener {


            settingsCount++

            if (settingsCount == 5){
                turnSettings = true
            }

           if (turnSettings){
               var intent = Intent(mContext, SettingsActivity::class.java)
               intent.putExtra("personInfo", data)
               startActivity(intent)
           }
        }


           tvMainPayMoney.setOnClickListener {

             var  SoftKeyboard = SPUtils.getInstance().getValue("SoftKeyboard",true) as Boolean

               if (SoftKeyboard){
                   var dialog = InputPhoneDialog(mContext)
                   dialog?.setListener(PhoneInputListener { phone ->
                       var serviceIntent = Intent(this, VoiceService::class.java)
                       serviceIntent.putExtra("voiceStr", phone + "元")
                       startService(serviceIntent)

                       val intent = Intent(mContext, PayActivity::class.java)
                       intent.putExtra("money", phone)
                       intent.putExtra("personInfo", data)
                       startActivity(intent)
                       Calculator.reset()

                   })
                   dialog?.show()

               }


       }



    }



    private fun initBanner(photoList: MutableList<String?>?) {
        bannerMain.visibility = View.VISIBLE
        bannerMain.setImageLoader(GlideImageLoader())
        bannerMain.setImages(photoList)
        bannerMain.setDelayTime(intervalTime)
        bannerMain.start()
    }


    override fun onStart() {
        super.onStart()


         turnSettings = false
         settingsCount = 0

        Calculator.reset()

        Log.e("onStart", "start")

        vip = SPUtils.getInstance().getValue("vip", true) as Boolean
        if (!vip) {
            btnConnUsb.visibility = GONE
        } else {
            btnConnUsb.visibility = VISIBLE

        }






        tvMainPayMoney.requestFocus()
        tvMainPayMoney.setText("")
        webView.visibility = GONE
        view.visibility = GONE

    }


    var exit = 156
    var cashPledge = 131
    var returnDeposit = 132
    var getLastOrderPrint = 143
    var returnMoney = 133
//    var cashPledge = 155
//    var returnDeposit = 154
    var deviceNo = Build.SERIAL
    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {

        Log.e("dispatchKeyEvent",event?.keyCode.toString())

    if ( event?.action != KeyEvent.ACTION_UP &&( event?.keyCode == 157) ) {
        p.getLastOrderPrint(deviceNo )
    }


        if (event?.keyCode == returnMoney) {

            val intent = Intent(mContext, ReturnMoneyActivity::class.java)
            startActivity(intent)
            Calculator.reset()

        }

        if (event?.keyCode == exit) {
            MaterialDialog.Builder(mContext)
                .title("提示")
                .content("退出登录")
                .positiveText("确定")
                .onPositive { dialog, which ->
                    p.logout()

                }
                .show()
        }

        if (event?.keyCode == cashPledge) {

            val intent = Intent(mContext, CashPledgeActivity::class.java)
            startActivity(intent)
            Calculator.reset()
            finish()

        }


        if (event?.keyCode == returnDeposit) {

            val intent = Intent(mContext, ReturnCashActivity::class.java)
            startActivity(intent)
            Calculator.reset()
            finish()

        }

    if (event?.action != KeyEvent.ACTION_UP) {

        Log.e("dispatchKeyEvent","Calculator")

        Calculator.onKeyEvent(
            when (event?.keyCode) {
                KeyEvent.KEYCODE_NUMPAD_1 -> Calculator.KeyCode._1
                KeyEvent.KEYCODE_NUMPAD_2 -> Calculator.KeyCode._2
                KeyEvent.KEYCODE_NUMPAD_3 -> Calculator.KeyCode._3
                KeyEvent.KEYCODE_NUMPAD_4 -> Calculator.KeyCode._4
                KeyEvent.KEYCODE_NUMPAD_5 -> Calculator.KeyCode._5
                KeyEvent.KEYCODE_NUMPAD_6 -> Calculator.KeyCode._6
                KeyEvent.KEYCODE_NUMPAD_7 -> Calculator.KeyCode._7
                KeyEvent.KEYCODE_NUMPAD_8 -> Calculator.KeyCode._8
                KeyEvent.KEYCODE_NUMPAD_9 -> Calculator.KeyCode._9
                KeyEvent.KEYCODE_NUMPAD_0 -> Calculator.KeyCode._0
                KeyEvent.KEYCODE_NUMPAD_DOT -> Calculator.KeyCode._D
                KeyEvent.KEYCODE_DEL -> Calculator.KeyCode._B
                else -> return super.onKeyDown(event!!.keyCode, event)
            }
        )


        tvMainPayMoney.requestFocus()
//        tvMainPayMoney.text


    }



    if (event?.keyCode != KeyEvent.KEYCODE_ENTER) {




        } else {

            if (Calculator.doSum().toDouble() == 0.0) {
                return super.onKeyDown(event?.keyCode, event)
            }

            val serviceIntent = Intent(mContext, VoiceService::class.java)
            serviceIntent.putExtra("voiceStr", Calculator.doSum() + "元")
            startService(serviceIntent)

            val intent = Intent(mContext, PayActivity::class.java)
            intent.putExtra("money", Calculator.doSum())
            startActivity(intent)
            Calculator.reset()
        }


        return super.dispatchKeyEvent(event)
    }


    override fun showLoadDialog() {
        loadDialog.show()
    }

    override fun onResume() {
        super.onResume()
        tvMainPayMoney.requestFocus()
        webView.visibility = GONE
        bannerMain.visibility = VISIBLE

    }

    override fun dismissLoadDialog() {
        loadDialog.dismiss()
    }

    override fun logoutSuccess() {
        startActivity(Intent(mContext, LoginActivity::class.java))
        finish()
    }

    override fun logoutFailed(msg: String) {
        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show()
    }

    override fun getAdvertList(data: AdvertBean?) {
//        advertBean = data
        val bannerList = data?.pic?.map {
            it?.url
        } as MutableList<String?>
        initBanner(bannerList)
    }

    override fun onDestroy() {
        super.onDestroy()
        p.detachView()
    }

}
